#ifndef TOOLS_THREADPOOL_H
#define TOOLS_THREADPOOL_H

#include "BlockQueue.h"
#include <vector>
#include <thread>
#include <functional>
#include <future>
#include <atomic>
#include "Global.h"

namespace Tool
{

class ExportAPI ThreadPool
{
public:
    explicit ThreadPool(size_t maxThreads = std::thread::hardware_concurrency(), size_t queueMaxSize = 1000);
    ~ThreadPool();

    template<typename F, typename... Args>
    auto PostTask(F&& f, Args&&... args)
        -> std::future<typename std::result_of<F(Args...)>::type>
    {
        using return_type = typename std::result_of<F(Args...)>::type;

        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...)
            );
        std::future<return_type> res = task->get_future();
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(m_stop)
            {
                throw std::runtime_error("enqueue on stopped ThreadPool");
            }

            m_tasks->Push([task = std::move(task)]() mutable { (*task)(); });
        }
        return res;
    }

    size_t GetActiveThreadCount() const;
    void WaitAll();
    void Stop();
private:
    void SetMaxThreads(size_t maxThreads);

private:
    void WorkerThread();

    std::vector<std::thread> m_workers;
    std::unique_ptr<BlockQueue<std::function<void()>>> m_tasks;
    std::atomic<size_t> m_activeThreads{0};
    std::atomic<bool> m_stop{false};
    std::mutex m_mutex;
    std::condition_variable m_cv;
};

} // namespace Tool

#endif // THREADPOOL_H
